'use client';

import { useEffect, useState } from 'react';
import { useMultiChainWallet } from '@/contexts/MultiChainWalletContext';

interface EVMWalletButtonProps {
  chain: 'bsc' | 'xlayer';
  className?: string;
}

interface EVMProvider {
  id: string;
  label: string;
  icon: string;
  provider: unknown;
}

export function EVMWalletButton({ chain, className = '' }: EVMWalletButtonProps) {
  const { connected, address, connectWallet, disconnectWallet } = useMultiChainWallet();
  const [showModal, setShowModal] = useState(false);
  const [connecting, setConnecting] = useState(false);
  const [providers, setProviders] = useState<EVMProvider[]>([]);

  // 检测可用的 EVM 钱包
  useEffect(() => {
    const detectProviders = () => {
      const w = window as unknown as { ethereum?: unknown };
      const eth = (w as unknown as { ethereum?: { providers?: unknown[] } }).ethereum as unknown;
      
      console.log('检测 EVM 钱包...', { ethereum: !!eth, chain });
      
      const list: EVMProvider[] = [];
      const pushUnique = (prov: unknown) => {
        if (!prov) return;
        const p = prov as Record<string, unknown>;
        let id = 'generic';
        let label = 'Browser Wallet';
        let icon = '🔗';
        
        if (p.isMetaMask) { 
          id = 'metamask'; 
          label = 'MetaMask'; 
          icon = '🦊';
        } else if (p.isOkxWallet || p.isOKExWallet) { 
          id = 'okx'; 
          label = 'OKX Wallet'; 
          icon = '⚫';
        } else if (p.isRabby) { 
          id = 'rabby'; 
          label = 'Rabby'; 
          icon = '🐰';
        } else if (p.isBitKeep) { 
          id = 'bitget'; 
          label = 'Bitget Wallet'; 
          icon = '🔷';
        }
        
        if (!list.find(i => i.id === id)) {
          list.push({ id, label, icon, provider: prov });
        }
      };

      if (eth && typeof eth === 'object' && Array.isArray((eth as Record<string, unknown>).providers as unknown[])) {
        ((eth as Record<string, unknown>).providers as unknown[]).forEach(pushUnique);
      } else if (eth) {
        pushUnique(eth);
      }

      console.log('检测到的钱包:', list);
      setProviders(list);
    };

    // 添加延迟确保页面加载完成
    const timer = setTimeout(detectProviders, 500);
    return () => clearTimeout(timer);
  }, [chain]);

  const handleConnect = async (provider: EVMProvider) => {
    try {
      setConnecting(true);
      // 临时设置选中的 provider
      (window as unknown as { ethereum?: unknown }).ethereum = provider.provider;
      await connectWallet(chain);
      setShowModal(false);
    } catch (error) {
      console.error('连接钱包失败:', error);
    } finally {
      setConnecting(false);
    }
  };

  const handleDisconnect = async () => {
    await disconnectWallet();
  };

  if (connected && address) {
    return (
      <div className="flex items-center gap-2">
        <span className="hidden md:inline font-mono text-[10px] text-green-500">
          {address.slice(0, 4)}...{address.slice(-4)}
        </span>
        <button
          onClick={handleDisconnect}
          className={`px-4 py-1.5 rounded text-xs font-medium bg-gray-200 hover:bg-gray-300 text-gray-700 ${className}`}
        >
          断开连接
        </button>
      </div>
    );
  }

  return (
    <>
      <button
        onClick={() => {
          console.log('EVMWalletButton 点击:', { chain, showModal });
          setShowModal(true);
        }}
        className={`px-4 py-1.5 rounded text-xs font-medium text-white shadow hover:brightness-110 ${className}`}
        disabled={connecting}
      >
        {connecting ? '连接中...' : 'Select Wallet'}
      </button>

      {/* Modal - 模仿 Solana 钱包选择样式 */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          {/* 背景遮罩 */}
          <div 
            className="fixed inset-0 bg-black bg-opacity-50"
            onClick={() => setShowModal(false)}
          />
          
          {/* Modal 内容 */}
          <div className="relative bg-white rounded-lg shadow-xl max-w-sm w-full mx-4 p-6">
            {/* 标题 */}
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold text-gray-900">
                Connect a wallet on {chain === 'bsc' ? 'BSC' : 'XLayer'} to continue
              </h3>
              <button
                onClick={() => setShowModal(false)}
                className="text-gray-400 hover:text-gray-600"
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            {/* 钱包列表 */}
            <div className="space-y-2">
              {providers.length === 0 ? (
                <div className="text-center py-8 text-gray-500">
                  <p className="mb-2">No wallet found</p>
                  <p className="text-sm">Please install a supported wallet extension</p>
                </div>
              ) : (
                providers.map((provider) => (
                  <button
                    key={provider.id}
                    onClick={() => handleConnect(provider)}
                    disabled={connecting}
                    className="w-full flex items-center gap-3 p-3 rounded-lg border border-gray-200 hover:border-gray-300 hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <span className="text-2xl">{provider.icon}</span>
                    <span className="font-medium text-gray-900">{provider.label}</span>
                    {connecting && (
                      <div className="ml-auto">
                        <div className="w-4 h-4 border-2 border-gray-300 border-t-blue-500 rounded-full animate-spin" />
                      </div>
                    )}
                  </button>
                ))
              )}
            </div>

            {/* 底部说明 */}
            <div className="mt-4 pt-4 border-t border-gray-200">
              <p className="text-xs text-gray-500 text-center">
                By connecting a wallet, you agree to the Terms of Service
              </p>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
